<template>
    <el-select
        v-on="$listeners"
        :value="value"
        v-bind="$attrs"
        @change="changeHandler"
    >
        <el-option
            v-for="(item, index) in option"
            :key="index"
            :label="item.value"
            :value="item.key"
        >
        </el-option>
    </el-select>
</template>
<script>
const defaultProps = {
    value: 'key',
    label: 'value'
}

export default {
    name: 'select-option',
    model: {
        prop: 'value',
        event: 'change'
    },
    props: {
        axios: {
            type: String,
            default: ''
        },
        formmat: {
            type: Object,
            required: false,
            default: () => {}
        },
        value: {
            default: ''
        },
        data: {
            type: Array,
            default: () => []
        },
        params: {
            type: Object,
            required: false,
            default: () => {}
        },
        isWatchParams: {
            type: Boolean,
            default: false
        }
    },
    computed: {
        props_() {
            return {
                ...defaultProps,
                ...this.formmat
            }
        },
        option() {
            return this.axios ? this.defaultData : this.data
        }
    },
    watch: {
        params() {
            this.isWatchParams && this.query()
        },
        axios() {
            this.query()
        }
    },
    created() {
        this.query()
    },
    data() {
        return {
            defaultData: []
        }
    },
    methods: {
        changeHandler(e) {
            this.$emit(
                'select',
                this.option.find(o => e === o.key)
            )
        },
        query() {
            if (this.axios) {
                this.$api[this.axios](this.params).then(data => {
                    this.defaultData = Array.isArray(data)
                        ? data.map(e => {
                              return {
                                  key: e[this.props_.value],
                                  value: e[this.props_.label],
                                  ...e
                              }
                          })
                        : data.data_list && Array.isArray(data.data_list)
                        ? data.data_list.map(e => {
                              return {
                                  key: e[this.props_.value],
                                  value: e[this.props_.label],
                                  ...e
                              }
                          })
                        : Object.entries(data).map(([key, value]) => {
                              return {
                                  key: Number(key),
                                  value: value
                              }
                          })
                })
            }
        }
    }
}
</script>
<style lang="scss" scoped></style>
